<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Config;
use app\common\model\PrizeRecord;
use app\common\tool\RedLock;
use app\common\tool\Result;
use think\facade\Cache;
use think\Response;
use think\response\Json;
use app\common\model\Prize as PrizeModel;

class Prize extends Base
{

    public function index(): Response
    {
        $result['awards'] = PrizeModel::getRandom($this->user->id);
        $result['red_coin'] = $this->user->assets->red_coin;
        $result['prize_red_coin'] = Cache::get('system')['prize_red_coin'];

        return Result::fastReturn(['code'=>1, 'msg'=>'success', 'data'=>$result]);
    }

    /**
     * @return Json
     * 原点 2022年10月22日10:28:28 抽奖
     */
    public function luck(): Response
    {
        list($startTime, $endTime) = explode(',', Cache::get('system')['prize_times']);
        if($startTime > time()) return Result::fail('抽奖活动尚未开始！');
        if($endTime < time()) return Result::fail('抽奖活动已结束！');
        $redLock = new RedLock([['127.0.0.1', 6379, 0.01]]);
        $lock = $redLock->lock('yusheng250124PrizeLuck', 20000);
        if (!$lock) {
            return Result::fail('服务器繁忙，请再试一次！');
        }
        try {
            $result = PrizeModel::luck($this->user);
            $redLock->unlock($lock);
            return Result::fastReturn($result);
        } catch (\Exception $e) {
            $redLock->unlock($lock);
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Json
     * 原点 2022年10月22日13:43:39 抽奖记录
     */
    public function record(): Response
    {
        return Result::fastReturn(PrizeRecord::getPageList(['uid' => $this->user->id], 'id,create_time,awards,order_id,product_info,status,type', $this->getPage(), $this->getLimit(), false));
    }
}

